﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing.Printing;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using C1.C1Report;
using C1.Win.C1Input;
using PCSComProduction.WorkOrder.BO;
using PCSComProduction.WorkOrder.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.DataContext;
using PCSComUtils.Framework.ReportFrame.BO;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
using PCSUtils.Framework.ReportFrame;
using PCSUtils.Log;
using PCSUtils.Utils;
using log4net;
using PRO_WorkingTime = PCSComUtils.Common.PRO_WorkingTime;

namespace PCSProduction.WorkOrder
{
    /// <summary>
    /// Summary description for WorkOrderCompletion.
    /// </summary>
    public partial class WorkOrderCompletion : Form
    {
        protected const string This = "PCSProduction.WorkOrder.WorkOrderCompletion";
        private const string VWorkOrderCompletion = "v_WorkOrderCompletion";
        private const string ReportfldTitle = "fldTitle";
        private const string CaptionUm = "UM";
        private const string LocationCode = "LocationCode";
        private const string BinCode = "BinCode";
        private const string VWocompletion = "v_WOCompletion";
        private const string PARTNUMBER = "PartNumber";
        private const string Partname = "PartName";
        private const string Model = "Model";
        private const string VWorelease = "V_WOReleaseForCompletion";
        private const string VWoreleasefgoodscode = "V_WOReleaseFGoodsCodeForCompletion";
        private readonly bool _closeForm;
        private readonly UtilsBO _boUtil = new UtilsBO();
        private readonly WorkOrderCompletionBO _boWoCompletion = new WorkOrderCompletionBO();
        private readonly MST_MasterLocationVO _voMasLoc = new MST_MasterLocationVO();
        private bool _hasError;
        private decimal _decOriginCompletedQty;
        private EnumAction _formMode = EnumAction.Default;
        private int _iProductIdEdit;
        private int _iWoDetailIdEdit;
        private int _intProductionLineId;
        private int _intTransTypeId;
        private decimal _pdecQuantity;
        private int _pintLotSize;
        private int _pintProductId;

        private ILog _logger = LogManager.GetLogger(typeof (WorkOrderCompletion));

        public WorkOrderCompletion()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Open form and close immediately
        /// </summary>
        /// <param name="blnClose"></param>
        public WorkOrderCompletion(bool blnClose)
        {
            InitializeComponent();
            _closeForm = blnClose;
        }

        #region BOM Shortage Report: Tuan TQ

        /// <summary>
        /// Print BOM Shortage Report
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ., 29 Dec, 2005</author>
        private void BtnPrintBomShortageClick(object sender, EventArgs e)
        {
            const string methodName = This + ".BtnPrintBomShortageClick()";
            try
            {
                //Change cursor to busy
                Cursor = Cursors.WaitCursor;

                ShowBomShortageReport();
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }


        private void ShowBomShortageReport()
        {
            const string bomShortageReport = "BOMShortageReport.xml";
            try
            {
                //return if no record was selected
                if (txtWOLine.Tag == null)
                {
                    return;
                }

                if (txtWOLine.Tag.ToString().Trim() == string.Empty)
                {
                    return;
                }

                //Change cursor type
                Cursor = Cursors.WaitCursor;

                //get completed quatity
                decimal decCompletedQuantity = decimal.Zero;
                if (!txtCompletedQty.ValueIsDbNull && txtCompletedQty.Text.Trim() != string.Empty)
                {
                    decCompletedQuantity = decimal.Parse(txtCompletedQty.Value.ToString());
                }

                int workOrderDetailId = Convert.ToInt32(txtWOLine.Tag);

                DataTable dtbResult = _boWoCompletion.GetBomShortageData(workOrderDetailId, decCompletedQuantity);

                // Check data source
                if (dtbResult == null || dtbResult.Rows.Count == 0)
                {
                    // enough component to complete, don't show the report
                    PCSMessageBox.Show(ErrorCode.MESSAGE_ENOUGHT_COMPONENT_TO_COMPLETE);
                    Cursor = Cursors.Default;
                    return;
                }

                #region show report

                var rptReport = new C1Report();
                string strReportPath = Path.Combine(Application.StartupPath, Constants.REPORT_DEFINITION_STORE_LOCATION);
                var reportFile = Path.Combine(strReportPath, bomShortageReport);
                if (!File.Exists(reportFile))
                {
                    Cursor = Cursors.Default;
                    PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
                    return;
                }
                var reportInfo = rptReport.GetReportInfo(reportFile);
                rptReport.Load(reportFile, reportInfo[0]);
                rptReport.Layout.PaperSize = PaperKind.A4;
                
                // set datasource object that provides data to report.
                rptReport.DataSource.Recordset = null;
                rptReport.DataSource.Recordset = dtbResult;
                if (rptReport.Fields["fldCompletedQuantity"] != null)
                {
                    rptReport.Fields["fldCompletedQuantity"].Value = decCompletedQuantity.ToString("#,##0");
                }
                // render report
                rptReport.Render();
                
                // render the report into the PrintPreviewControl
                var ppvViewer = new C1PrintPreviewDialog();
                ppvViewer.FormTitle = rptReport.Fields["fldTitle"].Text;
                ppvViewer.ReportViewer.NavigationPanelVisible = false;
                ppvViewer.ReportViewer.Document = rptReport.Document;
                ppvViewer.Show();

                #endregion
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
                // Log error message into log file.
                Logger.LogMessage(ex, "ShowBomShortageReport", Level.DEBUG);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        #endregion

        #region Print WO Completion: Tuan TQ

        /// <summary>
        /// Build and show WO Completion Slip Report
        /// </summary>
        /// <Author> Tuan TQ, 08 Dec, 2005</Author>
        private void ShowWoCompletionSlipReport()
        {
            const int numberOfCopies = 1;
            const string applicationPath = @"PCSMain\bin\Debug";
            const string rptCompanyField = "fldCompany";
            const string woCompletionSlipReport = "WOCompletionSlipReport.xml";

            //return if no record was selected
            if (lblCompletionNO.Tag == null)
            {
                return;
            }

            if (lblCompletionNO.Tag.ToString().Trim() == string.Empty)
            {
                return;
            }

            var printPreview = new C1PrintPreviewDialog();
            var boDataReport = new C1PrintPreviewDialogBO();

            DataTable dtbResult = boDataReport.GetWOCompletionData(int.Parse(lblCompletionNO.Tag.ToString()));

            // Check data source
            if (dtbResult != null)
            {
                //Prepare data for blank row				
                if (dtbResult.Rows.Count > 0)
                {
                    for (int i = 1; i < numberOfCopies; i++)
                    {
                        DataRow drowSourceBlankRow = dtbResult.NewRow();
                        //Copy data
                        for (int colIndex = 0; colIndex < dtbResult.Columns.Count; colIndex++)
                        {
                            drowSourceBlankRow[colIndex] = dtbResult.Rows[0][colIndex];
                        }
                        dtbResult.Rows.Add(drowSourceBlankRow);
                    }
                }
            }

            var reportBuilder = new ReportBuilder();

            //Get actual application path
            string strReportPath = Application.StartupPath;
            int intIndex = strReportPath.IndexOf(applicationPath, StringComparison.Ordinal);
            if (intIndex > -1)
            {
                strReportPath = strReportPath.Substring(0, intIndex);
            }

            strReportPath += strReportPath.Substring(strReportPath.Length - 1) == @"\"
                                 ? Constants.REPORT_DEFINITION_STORE_LOCATION
                                 : "\\" + Constants.REPORT_DEFINITION_STORE_LOCATION;

            //Set datasource and lay-out path for reports
            reportBuilder.SourceDataTable = dtbResult;
            reportBuilder.ReportDefinitionFolder = strReportPath;

            reportBuilder.ReportLayoutFile = woCompletionSlipReport;

            //check if layout is valid
            if (reportBuilder.AnalyseLayoutFile())
            {
                reportBuilder.UseLayoutFile = true;
            }
            else
            {
                PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
                return;
            }

            reportBuilder.MakeDataTableForRender();

            // and show it in preview dialog			
            reportBuilder.ReportViewer = printPreview.ReportViewer;
            reportBuilder.RenderReport();

            //Header information get from system params				
            reportBuilder.DrawPredefinedField(rptCompanyField, SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME));

            reportBuilder.RefreshReport();

            //Print report
            try
            {
                printPreview.FormTitle = reportBuilder.GetFieldByName(ReportfldTitle).Text;
            }
            catch
            {
                Logger.LogMessage("Unable to set Form title");
            }
            printPreview.Show();
        }

        private void BtnPrintClick(object sender, EventArgs e)
        {
            const string methodName = This + ".BtnPrintClick()";
            try
            {
                //Change cursor to busy
                Cursor = Cursors.WaitCursor;

                //Show report
                ShowWoCompletionSlipReport();
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        #endregion

        #region HACKED: Add more 3 properties, Tuan TQ

        //HACKED: Added by Tuan TQ. 09 Dec, 2005

        /// <summary>
        /// Fill related data on controls when selecting Shift
        /// </summary>
        /// <param name="pblnAlwaysShowDialog"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private bool SelectShift(bool pblnAlwaysShowDialog)
        {
            var htbCriteria = new Hashtable();

            //Call OpenSearchForm for selecting Shift
            DataRowView drwResult = FormControlComponents.OpenSearchForm(PRO_ShiftTable.TABLE_NAME, PRO_ShiftTable.SHIFTDESC_FLD,
                                                                         txtShift.Text, htbCriteria, pblnAlwaysShowDialog);

            // If has Shift matched searching condition, fill values to form's controls
            if (drwResult != null)
            {
                txtShift.Text = drwResult[PRO_ShiftTable.SHIFTDESC_FLD].ToString();
                txtShift.Tag = drwResult[PRO_ShiftTable.SHIFTID_FLD];

                //Reset modify status
                txtShift.Modified = false;
            }
            else if (!pblnAlwaysShowDialog)
            {
                txtShift.Tag = null;
                txtShift.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// Open Search Form for selecting location
        /// </summary>
        /// <param name="pblnAlwaysShowDialog"></param>
        /// <returns></returns>
        private bool SelectLocation(bool pblnAlwaysShowDialog)
        {
            //User has entered master location
            if (txtMasLoc.Text.Trim() == string.Empty)
            {
                PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_SELECTMASLOC, MessageBoxIcon.Exclamation);
                txtMasLoc.Focus();
                return false;
            }

            var htbCriteria = new Hashtable {{MST_LocationTable.MASTERLOCATIONID_FLD, txtMasLoc.Tag}};

            DataRowView drwResult = FormControlComponents.OpenSearchForm(MST_LocationTable.TABLE_NAME, MST_LocationTable.CODE_FLD,
                                                                         txtLocation.Text.Trim(), htbCriteria, pblnAlwaysShowDialog);
            // If has BIN matched searching condition, fill values to form's controls
            if (drwResult != null)
            {
                if (txtLocation.Tag == null)
                {
                    txtBin.Text = string.Empty;
                    txtBin.Tag = null;
                }
                else if (!txtLocation.Tag.Equals(drwResult[MST_LocationTable.LOCATIONID_FLD]))
                {
                    txtBin.Text = string.Empty;
                    txtBin.Tag = null;
                }

                txtLocation.Text = drwResult[MST_LocationTable.CODE_FLD].ToString();
                txtLocation.Tag = drwResult[MST_LocationTable.LOCATIONID_FLD];

                //reset Modified status
                txtLocation.Modified = false;

                txtBin.Enabled = bool.Parse(drwResult[MST_LocationTable.BIN_FLD].ToString());
                btnSearchBin.Enabled = bool.Parse(drwResult[MST_LocationTable.BIN_FLD].ToString());

                //Reset MasterLocationDefaultID
            }
            else if (!pblnAlwaysShowDialog)
            {
                txtLocation.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// Open Search Form for selecting bin
        /// </summary>
        /// <param name="pblnAlwaysShowDialog"></param>
        /// <returns></returns>
        private bool SelectBin(bool pblnAlwaysShowDialog)
        {
            //User has entered Location
            if (txtLocation.Text.Trim() == string.Empty)
            {
                PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_SELECTLOC, MessageBoxIcon.Exclamation);
                txtLocation.Focus();
                return false;
            }

            string strCondition = MST_BINTable.TABLE_NAME + "." + MST_BINTable.LOCATIONID_FLD + " = " + txtLocation.Tag;
            strCondition += " AND MST_BIN." + MST_BINTable.BINTYPEID_FLD + " != " + ((int) BinTypeEnum.LS).ToString(CultureInfo.InvariantCulture);
            
            DataRowView drwResult = FormControlComponents.OpenSearchForm(MST_BINTable.TABLE_NAME, MST_BINTable.CODE_FLD,
                                                                         txtBin.Text.Trim(), strCondition);
            // If has BIN matched searching condition, fill values to form's controls
            if (drwResult != null)
            {
                txtBin.Text = drwResult[MST_BINTable.CODE_FLD].ToString();
                txtBin.Tag = drwResult[MST_BINTable.BINID_FLD];

                //Reset modify status
                txtBin.Modified = false;
            }
            else if (!pblnAlwaysShowDialog)
            {
                txtBin.Tag = null;
                txtBin.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// Fill related data on controls when selecting Issue purpose
        /// </summary>
        /// <param name="pblnAlwaysShowDialog"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private bool SelectIssuePurpose(bool pblnAlwaysShowDialog)
        {
            var htbCriteria = new Hashtable {{PRO_IssuePurposeTable.TRANTYPEID_FLD, _intTransTypeId}};

            //Call OpenSearchForm for selecting Issue purpose
            DataRowView drwResult = FormControlComponents.OpenSearchForm(PRO_IssuePurposeTable.TABLE_NAME,
                                                                         PRO_IssuePurposeTable.DESCRIPTION_FLD, txtPurpose.Text,
                                                                         htbCriteria, pblnAlwaysShowDialog);

            // If has Issue Purpose matched searching condition, fill values to form's controls
            if (drwResult != null)
            {
                txtPurpose.Text = drwResult[PRO_IssuePurposeTable.DESCRIPTION_FLD].ToString();
                txtPurpose.Tag = drwResult[PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD];

                //Reset modify status
                txtPurpose.Modified = false;
            }
            else if (!pblnAlwaysShowDialog)
            {
                txtPurpose.Tag = null;
                txtPurpose.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// Processing click event on btnPurpose
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private void BtnPurposeClick(object sender, EventArgs e)
        {
            const string methodName = This + ".BtnPurposeClick()";
            try
            {
                SelectIssuePurpose(true);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Processing Validating event on txtPurpose
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private void TxtPurposeValidating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".TxtPurposeValidating()";

            try
            {
                //exit if not in add action or empty
                if (!btnSave.Enabled) return;

                if (txtPurpose.Text.Trim().Length == 0)
                {
                    txtPurpose.Tag = null;
                    return;
                }
                if (!txtPurpose.Modified)
                {
                    return;
                }

                e.Cancel = !SelectIssuePurpose(false);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Processing Keydown event on txtPurpose
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private void TxtPurposeKeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".TxtPurposeKeyDown()";

            try
            {
                if ((e.KeyCode == Keys.F4) && (btnPurpose.Enabled))
                {
                    SelectIssuePurpose(true);
                }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Processing click event on btnShift
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private void BtnShiftClick(object sender, EventArgs e)
        {
            const string methodName = This + ".BtnShiftClick()";

            try
            {
                SelectShift(true);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Processing KeyDown event on txtShift
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private void TxtShiftKeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".TxtShiftKeyDown()";

            try
            {
                if ((e.KeyCode == Keys.F4) && (btnShift.Enabled))
                {
                    SelectShift(true);
                }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Processing Validating event on txtShift
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author> Tuan TQ. 09 Dec, 2005</author>
        private void TxtShiftValidating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".TxtShiftValidating()";

            try
            {
                //exit if not in add action or empty
                if (!btnSave.Enabled) return;

                if (txtShift.Text.Trim().Length == 0)
                {
                    txtShift.Tag = null;
                    return;
                }
                if (!txtShift.Modified)
                {
                    return;
                }

                e.Cancel = !SelectShift(false);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        /// <summary>
        /// WorkOrderCompletion_Load
        /// </summary>
        /// <author>Trada</author>
        /// <date>Thursday, June 16 2005</date>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WorkOrderCompletion_Load(object sender, EventArgs e)
        {
            const string methodName = This + ".WorkOrderCompletion_Load()";
            try
            {
                //Set authorization for user
                var objSecurity = new Security();
                Name = This;
                if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
                {
                    Close();
                    // You don't have the right to view this item
                    PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
                    return;
                }
                if (_closeForm)
                {
                    Close();
                    return;
                }
                // Load combo box
                DataSet dstCcn = _boUtil.ListCCN();
                cboCCN.DataSource = dstCcn.Tables[MST_CCNTable.TABLE_NAME];
                cboCCN.DisplayMember = MST_CCNTable.CODE_FLD;
                cboCCN.ValueMember = MST_CCNTable.CCNID_FLD;
                FormControlComponents.PutDataIntoC1ComboBox(cboCCN, dstCcn.Tables[MST_CCNTable.TABLE_NAME],
                                                            MST_CCNTable.CODE_FLD, MST_CCNTable.CCNID_FLD,
                                                            MST_CCNTable.TABLE_NAME);
                if (SystemProperty.CCNID != 0)
                {
                    cboCCN.SelectedValue = SystemProperty.CCNID;
                }
                txtMasLoc.Focus();
                btnSave.Enabled = false;
                btnPrint.Enabled = false;

                btnPrintBOMShortage.Enabled = false;
                
                //Reset form
                _formMode = EnumAction.Default;
                //Set default Master Location
                FormControlComponents.SetDefaultMasterLocation(txtMasLoc);
                _voMasLoc.MasterLocationID = SystemProperty.MasterLocationID;

                //Set default for QA Status 
                cboQAStatus.SelectedIndex = (int) QAStatusEnum.Passed;

                //set format for datetime
                dtmPostDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
                dtmWOCompletionDate.CustomFormat = Constants.DATETIME_FORMAT;
                //HACK: added by TuanTQ 03 Apr, 2006. Fix error no. 3627. 
                txtCompletedQty.FormatType = FormatTypeEnum.CustomFormat;
                txtCompletedQty.CustomFormat = Constants.INTERGER_NUMBERFORMAT;

                txtNGQuantity.FormatType = FormatTypeEnum.CustomFormat;
                txtNGQuantity.CustomFormat = Constants.INTERGER_NUMBERFORMAT;
                //End hack
                LockForm();
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// ResetForm
        /// </summary>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private void ResetForm()
        {
            const string methodName = This + ".ResetForm()";
            try
            {
                dtmPostDate.Enabled = false;
                txtWO.Enabled = false;
                txtWOLine.Enabled = false;
                txtPartName.Enabled = false;
                txtModel.Enabled = false;
                txtItem.Enabled = false;
                txtLot.Enabled = false;
                txtSerial.Enabled = false;
                txtCompletedQty.Enabled = false;
                txtBin.Enabled = false;
                cboQAStatus.Enabled = false;
                txtLocation.Enabled = false;
                txtBin.Enabled = false;
                btnSearchBin.Enabled = false;
                btnSearchLocation.Enabled = false;
                btnSearchWO.Enabled = false;
                btnSearchWOLine.Enabled = false;

                //HACKED added by Tuan TQ
                txtShift.Enabled = false;
                btnShift.Enabled = false;
                txtPurpose.Enabled = false;
                btnPurpose.Enabled = false;
                txtRemark.Enabled = false;
                //End hacked
            }
            catch (PCSException ex)
            {
                throw new PCSException(ex.mCode, methodName, ex);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// ClearForm
        /// </summary>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void ClearForm()
        {
            txtWO.Text = string.Empty;
            txtWOLine.Text = string.Empty;
            txtWOLine.Tag = string.Empty;
            txtPartName.Text = string.Empty;
            txtModel.Text = String.Empty;
            txtItem.Text = string.Empty;
            txtLot.Text = string.Empty;
            txtSerial.Text = string.Empty;
            txtCompletedQty.Value = null;
            txtOrderQuantity.Value = null;
            txtTotalCompleted.Value = null;
            txtNGQuantity.Value = null;
            txtBin.Text = string.Empty;
            cboQAStatus.SelectedIndex = 0;
            txtLocation.Text = string.Empty;
            txtBin.Text = string.Empty;
            txtUM.Text = string.Empty;
            txtFGoodsCode.Text = string.Empty;
            if (_formMode == EnumAction.Default)
            {
                txtCompletionNo.Text = string.Empty;
            }

            //HACKED by Tuan TQ. Add properties
            txtShift.Text = string.Empty;
            txtPurpose.Text = string.Empty;
            txtRemark.Text = string.Empty;

            txtShift.Tag = null;
            txtPurpose.Tag = null;
            //End hacked
        }

        /// <summary>
        /// btnAdd_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnAdd_Click()";
            try
            {
                _formMode = EnumAction.Add;
                ClearForm();
                dtmPostDate.Value = (new UtilsBO()).GetDBDate();
                lblDate.Text = dtmPostDate.Text;
                txtMasLoc.Text = string.Empty;
                txtCompletionNo.Text = FormControlComponents.GetNoByMask(this);
                //Set focus to PostDate
                dtmPostDate.Enabled = true;
                dtmPostDate.Focus();
                //Fill Default Master Location 
                FormControlComponents.SetDefaultMasterLocation(txtMasLoc);
                _voMasLoc.MasterLocationID = SystemProperty.MasterLocationID;
                //HACKED added by Tuan TQ

                //CanhNV
                LockForm();
                //End.
                dtmWOCompletionDate.Value = null;
                //set default for QA Status 
                cboQAStatus.SelectedIndex = (int) QAStatusEnum.Passed;

                //fill Purpose Default
                _intTransTypeId =
                    new UtilsBO().GetTransTypeIDByCode(TransactionTypeEnum.PROWorkOrderCompletion.ToString());
                DataTable dtbPurpose = new UtilsBO().GetPurposeByTransTypeID(_intTransTypeId);
                if (dtbPurpose.Rows.Count == 1)
                {
                    txtPurpose.Text = dtbPurpose.Rows[0][PRO_IssuePurposeTable.DESCRIPTION_FLD].ToString();
                    txtPurpose.Tag = (int) dtbPurpose.Rows[0][PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD];
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// btnSave_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private void btnSave_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSave_Click()";
            string strProductCode = "";
            try
            {
                if (PCSMessageBox.Show(ErrorCode.MESSAGE_CONFIRM_BEFORE_SAVE_WOCOMPLETION, MessageBoxButtons.YesNo,
                                       MessageBoxIcon.Question, MessageBoxDefaultButton.Button2,
                                       new[] {dtmPostDate.Text}) == DialogResult.Yes)
                {
                    _hasError = true;

                    if (Security.IsDifferencePrefix(this, lblCompletionNO, txtCompletionNo))
                    {
                        return;
                    }

                    if (IsValidateData())
                    {
                        var voWoCompletion = new PRO_WorkOrderCompletion();
                        
                        if (txtShift.Text.Trim() != string.Empty)
                        {
                            voWoCompletion.ShiftID = int.Parse(txtShift.Tag.ToString());
                        }
                        voWoCompletion.IssuePurposeID = int.Parse(txtPurpose.Tag.ToString());
                        voWoCompletion.Remark = txtRemark.Text.Trim();
                        if (dtmWOCompletionDate.Value != null && dtmWOCompletionDate.Value != DBNull.Value)
                        {
                            voWoCompletion.CompletedDate = (DateTime) dtmWOCompletionDate.Value;
                        }
                        else
                        {
                            voWoCompletion.CompletedDate = DateTime.MinValue;
                        }
                        voWoCompletion.PostDate = DateTime.Parse(dtmPostDate.Value.ToString());
                        voWoCompletion.MasterLocationID = _voMasLoc.MasterLocationID;
                        voWoCompletion.WOCompletionNo = txtCompletionNo.Text;
                        if (_formMode == EnumAction.Edit)
                        {
                            voWoCompletion.WorkOrderCompletionID = int.Parse(lblCompletionNO.Tag.ToString());
                        }
                        voWoCompletion.WorkOrderMasterID = int.Parse(txtWO.Tag.ToString());
                        voWoCompletion.WorkOrderDetailID = int.Parse(txtWOLine.Tag.ToString());
                        voWoCompletion.ProductID = _pintProductId;
                        voWoCompletion.LocationID = int.Parse(txtLocation.Tag.ToString());
                        voWoCompletion.CCNID = int.Parse(cboCCN.SelectedValue.ToString());
                        voWoCompletion.CompletedQuantity = Decimal.Parse(txtCompletedQty.Value.ToString());
                        voWoCompletion.StockUMID = int.Parse(txtUM.Tag.ToString());
                        //Get value of QAStatus combo box
                        voWoCompletion.QAStatus = (byte) cboQAStatus.SelectedIndex;
                        voWoCompletion.Lot = string.Empty;
                        voWoCompletion.Serial = string.Empty;
                        if (txtBin.Text != string.Empty)
                        {
                            voWoCompletion.BinID = (int) txtBin.Tag;
                        }

                        DateTime dtmServerDate = _boUtil.GetDBDate();
                        var dsWoCompletion = new PRO_WorkOrderCompletionDS();
                        DataTable dtbCheckSubtract = dsWoCompletion.GetAvailableQuantityByProductionLinePostDate(dtmServerDate.AddDays(1),
                                                                                        _intProductionLineId,
                                                                                        voWoCompletion.WorkOrderDetailID);
                        DataTable dtbListOfComponentShortage = new PRO_WOBOMDS().ListComponentByWODetail(voWoCompletion.WorkOrderDetailID);

                        bool isAdded = false;
                        if (_formMode == EnumAction.Add)
                        {
                            isAdded = _boWoCompletion.InsertWorkOrderCompletion(voWoCompletion, _intProductionLineId,
                                                                               _pdecQuantity, dtmServerDate,
                                                                               dtbListOfComponentShortage,
                                                                               dtbCheckSubtract);
                        }
                        else if (_formMode == EnumAction.Edit)
                        {
                            //5. Get BomInfo of Product
                            var objWoBomDs = new PRO_WOBOMDS();
                            DataTable dtBomlist = objWoBomDs.ListBomDetailOfProduct(_iProductIdEdit, _iWoDetailIdEdit);
                            strProductCode = _boWoCompletion.UpdateWorkOrderCompletion(voWoCompletion, dtmServerDate,
                                                                                      dtBomlist);
                        }
                        if (isAdded)
                        {
                            PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
                        }
                        else
                        {
                            PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_SAVE_TO_DB);
                            return;
                        }
                        Security.UpdateUserNameModifyTransaction(this,
                                                                 PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD,
                                                                 voWoCompletion.WorkOrderCompletionID);
                        lblCompletionNO.Tag = voWoCompletion.WorkOrderCompletionID;


                        //Change Mode and disable all fields
                        _formMode = EnumAction.Default;
                        ResetForm();
                        LockForm();
                        btnAdd.Focus();
                    }
                }
            }
            catch (PCSException ex)
            {
                if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE)
                {
                    txtCompletedQty.Focus();
                    txtCompletedQty.SelectAll();
                    if (!dtmPostDate.Enabled)
                    {
                        if (PCSMessageBox.Show(ex.mCode, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                        {
                            ShowBomShortageReport();
                        }
                    }
                    else
                    {
                        var strParam = new string[1];
                        strParam[0] = ex.mMethod;
                        //Show message
                        PCSMessageBox.Show(ErrorCode.MESSAGE_NOT_ENOUGH_QUANTITY_OF_COMPONENT_TO_COMPLETE,
                                           MessageBoxIcon.Warning, strParam);
                    }
                }
                else
                {
                    // Displays the error message if throwed from PCSException.
                    PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);

                    //Check if WOCompletionNo was duplicated
                    if (ex.mCode == ErrorCode.DUPLICATE_KEY)
                    {
                        txtCompletionNo.Focus();
                        txtCompletionNo.Select();
                    }
                }

                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                if (strProductCode.Trim() != "")
                {
                    var ex1 = new PCSException();
                    var strParam = new string[1];
                    strParam[0] = ex1.mMethod;
                    PCSMessageBox.Show(ErrorCode.MESSAGE_NOT_ENOUGH_QUANTITY_OF_COMPONENT_TO_COMPLETE,
                                       MessageBoxIcon.Warning, strParam);
                }
                else
                {
                    PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                }
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// btnClose_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// WorkOrderCompletion_Closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, October 25 2005</date>
        private void WorkOrderCompletion_Closing(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".WorkOrderCompletion_Closing()";
            try
            {
                if (_formMode != EnumAction.Default)
                {
                    DialogResult confirmDialog = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE,
                                                                    MessageBoxButtons.YesNoCancel,
                                                                    MessageBoxIcon.Question);
                    switch (confirmDialog)
                    {
                        case DialogResult.Yes:
                            //Save before exit
                            btnSave_Click(btnSave, new EventArgs());
                            if (_hasError)
                            {
                                e.Cancel = true;
                            }
                            break;
                        case DialogResult.No:
                            break;
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// btnSearchCompletionNo_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void btnSearchCompletionNo_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSearchCompletionNo_Click()";
            try
            {
                if (_formMode == EnumAction.Default)
                {
                    var htbCriteria = new Hashtable();
                    //User has enter MasLoc
                    if (txtMasLoc.Text != string.Empty)
                    {
                        htbCriteria.Add(PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD, _voMasLoc.MasterLocationID.ToString(CultureInfo.InvariantCulture));
                    }
                    else //User has not entered MasLoc
                    {
                        PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_MASTERLOCATION, MessageBoxIcon.Error);
                        txtMasLoc.Focus();
                        return;
                    }
                    DataRowView drwResult = FormControlComponents.OpenSearchForm(VWorkOrderCompletion,
                                                                                 PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD,
                                                                                 txtCompletionNo.Text.Trim(), htbCriteria, true);
                    if (drwResult != null)
                    {
                        txtCompletionNo.Text = drwResult[PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD].ToString();
                        //Keep valua of WOCompletionID and ProductID
                        lblCompletionNO.Tag = drwResult[PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD];
                        txtCompletionNo.Tag = drwResult[PRO_WorkOrderCompletionTable.PRODUCTID_FLD];
                        FillDataToControlsForView(int.Parse(lblCompletionNO.Tag.ToString()),
                                                  int.Parse(txtCompletionNo.Tag.ToString()));
                        _voMasLoc.MasterLocationID =
                            int.Parse(drwResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString());
                        txtWO.Tag = drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD];
                        txtWOLine.Tag = drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD];
                        _iWoDetailIdEdit = Convert.ToInt32(drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD]);
                        txtUM.Tag = drwResult[PRO_WorkOrderDetailTable.STOCKUMID_FLD];
                        txtLocation.Tag = drwResult[MST_LocationTable.LOCATIONID_FLD];
                        txtBin.Tag = drwResult[MST_BINTable.BINID_FLD];
                        _iProductIdEdit = _pintProductId = (int) drwResult[ITM_ProductTable.PRODUCTID_FLD];
                        txtFGoodsCode.Text = drwResult[SO_SaleOrderDetailTable.FGOODSCODE_FLD].ToString();

                        //reset Modified status
                        txtCompletionNo.Modified = false;
                        LockForm();
                    }
                    else
                        txtCompletionNo.Focus();
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// btnSearchMasLoc_Click
        /// </summary>
        /// <author>Trada</author>
        /// <date>Thursday, June 16 2005</date>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchMasLoc_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSearchMasLoc_Click()";
            try
            {
                var htbCriteria = new Hashtable
                                      {
                                          {
                                              MST_MasterLocationTable.CCNID_FLD,
                                              cboCCN.SelectedIndex != -1 ? cboCCN.SelectedValue : 0
                                              }
                                      };
                //User has selected CCN

                DataRowView drwResult = FormControlComponents.OpenSearchForm(MST_MasterLocationTable.TABLE_NAME,
                                                                             MST_MasterLocationTable.CODE_FLD, txtMasLoc.Text.Trim(),
                                                                             htbCriteria, true);
                if (drwResult != null)
                {
                    if (_voMasLoc.MasterLocationID !=
                        int.Parse(drwResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString()))
                    {
                        _voMasLoc.MasterLocationID =
                            int.Parse(drwResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString());
                        ClearForm();
                    }
                    txtMasLoc.Text = drwResult[MST_MasterLocationTable.CODE_FLD].ToString();

                    //reset Modified status
                    txtMasLoc.Modified = false;
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// FillWOCompletionDate
        /// </summary>
        /// <param name="pdtmPostDate"></param>
        /// <param name="pintProductionLineID"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, July 19 2006</date>
        private bool FillWOCompletionDate(DateTime pdtmPostDate, int pintProductionLineID)
        {
            var boWorkOrderCompletion = new WorkOrderCompletionBO();
            var dstWorkingTime = new DataSet();
            int intYear = pdtmPostDate.Year;
            int intMonth = pdtmPostDate.Month;
            var dtmWOCompDate = new DateTime();
            dstWorkingTime = boWorkOrderCompletion.GetWorkingTimeByProductionLineAndYearMonth(pintProductionLineID,
                                                                                              intYear, intMonth);
            if (dstWorkingTime.Tables[0].Rows.Count == 1)
            {
                var dtmStartTimeFromDB = (DateTime) dstWorkingTime.Tables[0].Rows[0][PRO_WorkingTime.STARTTIME_FLD];
                //Build StartTime and EndTime 
                var dtmStartTime = new DateTime(pdtmPostDate.Year, pdtmPostDate.Month, pdtmPostDate.Day,
                                                dtmStartTimeFromDB.Hour, dtmStartTimeFromDB.Minute, 0);
                DateTime dtmEndTime = dtmStartTime.AddHours(24);
                if (pdtmPostDate >= dtmStartTime && pdtmPostDate <= dtmEndTime)
                {
                    dtmWOCompDate = new DateTime(pdtmPostDate.Year, pdtmPostDate.Month, pdtmPostDate.Day, 0, 0, 0);
                }
                else
                {
                    dtmWOCompDate = pdtmPostDate.AddDays(-1);
                    dtmWOCompDate = new DateTime(dtmWOCompDate.Year, dtmWOCompDate.Month, dtmWOCompDate.Day);
                }
                dtmWOCompletionDate.Value = dtmWOCompDate;
                return true;
            }
            else
            {
                var dtmStartTimeFromDB = new DateTime(pdtmPostDate.Year, pdtmPostDate.Month, pdtmPostDate.Day, 6, 15, 0);
                var dtmStartTime = new DateTime(pdtmPostDate.Year, pdtmPostDate.Month, pdtmPostDate.Day,
                                                dtmStartTimeFromDB.Hour, dtmStartTimeFromDB.Minute, 0);
                if (pdtmPostDate >= dtmStartTime)
                {
                    dtmWOCompDate = new DateTime(pdtmPostDate.Year, pdtmPostDate.Month, pdtmPostDate.Day, 0, 0, 0);
                }
                else
                {
                    dtmWOCompDate = pdtmPostDate.AddDays(-1);
                    dtmWOCompDate = new DateTime(dtmWOCompDate.Year, dtmWOCompDate.Month, dtmWOCompDate.Day);
                }
                dtmWOCompletionDate.Value = dtmWOCompDate;

                return false;
            }
        }

        /// <summary>
        /// btnSearchWO_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Monday, June 20 2005</date>
        private void btnSearchWO_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSearchWO_Click()";
            try
            {
                var htbCriteria = new Hashtable();
                DataRowView drwResult = null;
                //User has entered MasLoc
                if (txtMasLoc.Text != string.Empty)
                {
                    htbCriteria.Add(PRO_WorkOrderMasterTable.MASTERLOCATIONID_FLD, _voMasLoc.MasterLocationID.ToString());
                }
                else //User has not entered MasLoc
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_MASTERLOCATION, MessageBoxIcon.Error);
                    txtMasLoc.Focus();
                    return;
                }

                //User has entered FGoodsCode
                if (txtFGoodsCode.Text != string.Empty)
                    htbCriteria.Add(SO_SaleOrderDetailTable.FGOODSCODE_FLD, txtFGoodsCode.Text);

                htbCriteria.Add(PRO_WorkOrderDetailTable.STATUS_FLD, (int) WOLineStatus.Released);

                if (txtFGoodsCode.Text.Trim() == string.Empty)
                {
                    drwResult = FormControlComponents.OpenSearchForm(VWorelease,
                                                                     PRO_WorkOrderMasterTable.WORKORDERNO_FLD,
                                                                     txtWO.Text.Trim(), htbCriteria, true);
                }
                else
                {
                    drwResult = FormControlComponents.OpenSearchForm(VWoreleasefgoodscode,
                                                                     PRO_WorkOrderMasterTable.WORKORDERNO_FLD,
                                                                     txtWO.Text.Trim(), htbCriteria, true);
                }
                if (drwResult != null)
                {
                    if (!drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD].Equals(txtWO.Tag))
                    {
                        txtWO.Tag = drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD];
                        ClearFormWhenChangeWOLine();
                        dtmWOCompletionDate.Value = null;
                        txtWOLine.Text = string.Empty;
                    }
                    txtWO.Text = drwResult[PRO_WorkOrderMasterTable.WORKORDERNO_FLD].ToString();
                    lblWO.Tag = drwResult[PRO_WorkOrderMasterTable.PRODUCTIONLINEID_FLD];
                    //reset Modified status
                    txtWO.Modified = false;
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// ClearFormWhenChangeWOLine
        /// </summary>
        /// <author>Trada</author>
        /// <date>Thursday, June 23 2005</date>
        private void ClearFormWhenChangeWOLine()
        {
            const string methodName = This + ".ClearFormWhenChangeWOLine()";
            try
            {
                txtPartName.Text = string.Empty;
                txtItem.Text = string.Empty;
                txtModel.Text = string.Empty;
                txtUM.Text = string.Empty;
                cboQAStatus.SelectedIndex = 0;
                txtLot.Text = string.Empty;
                txtSerial.Text = string.Empty;
                txtBin.Text = string.Empty;
                txtCompletedQty.Value = null;
            }
            catch (PCSException ex)
            {
                throw new PCSException(ex.mCode, methodName, ex);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// btnSearchLocation_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private void btnSearchLocation_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSearchLocation_Click()";
            try
            {
                SelectLocation(true);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// btnSearchBin_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Tuan TQ</author>
        /// <date>Apr 03, 2006</date>
        private void btnSearchBin_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSearchBin_Click()";
            try
            {
                SelectBin(true);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// btnSearchWOLine_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void btnSearchWOLine_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnSearchWOLine_Click()";
            if (lblWO.Tag == null)
            {
                MessageBox.Show("Hãy nhập lệnh sản xuất cho XN");
                txtWO.Focus();
                return;
            }
            try
            {
                var htbCriteria = new Hashtable();
                htbCriteria.Add(PRO_WorkOrderDetailTable.PRODUCTIONLINEID_FLD, lblWO.Tag.ToString());
                DataRowView drwResult = null;
                //User has entered Work Order Master
                if (txtWO.Text != string.Empty)
                {
                    htbCriteria.Add(PRO_WorkOrderDetailTable.WORKORDERMASTERID_FLD, txtWO.Tag.ToString());
                    htbCriteria.Add(PRO_WorkOrderDetailTable.STATUS_FLD, (int) WOLineStatus.Released);
                }
                else //User has not entered Work Order Master
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_WOROUTING_INPUT_WORKORDER_FIRST, MessageBoxIcon.Error);
                    txtWO.Focus();

                    //HACKED added by Tuan TQ. Enable/Disable print BOM shortage
                    btnPrintBOMShortage.Enabled = false;
                    //End hacked
                    return;
                }

                drwResult = FormControlComponents.OpenSearchForm(VWocompletion, PRO_WorkOrderDetailTable.LINE_FLD,
                                                                 txtWOLine.Text.Trim(), htbCriteria, true);
                if (drwResult != null)
                {
                    if (!drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD].Equals(txtWOLine.Tag))
                    {
                        txtWOLine.Tag = drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD];
                        ClearFormWhenChangeWOLine();
                    }
                    txtCompletionNo.Text = FormControlComponents.GetNoByMask(this, drwResult["ProductionLineID_Code"].ToString().Trim());
                    _intProductionLineId = (int) drwResult[PRO_ProductionLineTable.PRODUCTIONLINEID_FLD];
                    if (dtmPostDate.Value != DBNull.Value && dtmPostDate.Value != null)
                        FillWOCompletionDate((DateTime) dtmPostDate.Value, _intProductionLineId);

                    txtWOLine.Text = drwResult[PRO_WorkOrderDetailTable.LINE_FLD].ToString();

                    //reset Modified status
                    txtWOLine.Modified = false;

                    new WorkOrderCompletionBO().ListLocationIssueAndOH(
                        int.Parse(drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD].ToString()), 1000);
                    _pintProductId = int.Parse(drwResult[PRO_WorkOrderDetailTable.PRODUCTID_FLD].ToString());

                    //FillDataToControls
                    txtItem.Text = drwResult[PARTNUMBER].ToString();
                    txtPartName.Text = drwResult[Partname].ToString();
                    txtModel.Text = drwResult[Model].ToString();

                    //Fill data to OpenQuantity
                    decimal pdecComplettedQuantity = drwResult[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].ToString() != string.Empty ? decimal.Parse(drwResult[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].ToString()) : 0;
                    decimal pdecScrapQuantity = drwResult[PRO_AOScrapDetailTable.SCRAPQUANTITY_FLD].ToString() != string.Empty ? decimal.Parse(drwResult[PRO_AOScrapDetailTable.SCRAPQUANTITY_FLD].ToString()) : 0;
                    decimal decOrderQuantity = decimal.Parse(drwResult[PRO_WorkOrderDetailTable.ORDERQUANTITY_FLD].ToString());
                    _pdecQuantity = decOrderQuantity - pdecComplettedQuantity - pdecScrapQuantity;
                    txtCompletedQty.Value = _pdecQuantity;
                    // store the order quantity in order to check total completed quantity
                    txtOrderQuantity.Value = decOrderQuantity;
                    txtTotalCompleted.Value = pdecComplettedQuantity;
                    //Fill data to UM label
                    txtUM.Text = drwResult[CaptionUm].ToString();
                    //Keep value of StockUMID
                    txtUM.Tag = drwResult[PRO_WorkOrderDetailTable.STOCKUMID_FLD];
                    //Set value for pintLotSize
                    _pintLotSize = drwResult[ITM_ProductTable.LOTSIZE_FLD].ToString() == string.Empty ? 0 : int.Parse(drwResult[ITM_ProductTable.LOTSIZE_FLD].ToString());
                    
                    //Fill data to combo box QAStatus
                    int pintQAStatus = 0;
                    if (drwResult[ITM_ProductTable.QASTATUS_FLD].ToString().Trim() != string.Empty ||
                        drwResult[ITM_ProductTable.QASTATUS_FLD] != DBNull.Value)
                        pintQAStatus = int.Parse(drwResult[ITM_ProductTable.QASTATUS_FLD].ToString());
                    switch (pintQAStatus)
                    {
                        case (int) EnumQA.NOT_REQUIRE_INSPECTION:
                            cboQAStatus.SelectedIndex = (int) QAStatusEnum.Passed;
                            break;
                        default:
                            cboQAStatus.SelectedIndex = (int) QAStatusEnum.Unknow;
                            break;
                    }
                    cboQAStatus.Enabled = false;
                }
                else
                {
                    txtWOLine.Focus();
                    //HACKED added by Tuan TQ. Enable/Disable print BOM shortage
                    btnPrintBOMShortage.Enabled = false;
                    //End hacked
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// txtMasLoc_Leave
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private void txtMasLoc_Leave(object sender, EventArgs e)
        {
            const string methodName = This + ".txtMasLoc_Leave()";
            try
            {
                OnLeaveControl(sender, e);
                if (!txtMasLoc.Modified) return;
                if (txtMasLoc.Text.Trim() == string.Empty)
                {
                    ClearForm();
                    if (btnAdd.Enabled)
                    {
                        dtmPostDate.Value = null;
                    }
                    return;
                }
                var htbCriteria = new Hashtable();
                //User has selected CCN
                htbCriteria.Add(MST_MasterLocationTable.CCNID_FLD, cboCCN.SelectedIndex != -1 ? cboCCN.SelectedValue : 0);
                DataRowView drwResult = FormControlComponents.OpenSearchForm(MST_MasterLocationTable.TABLE_NAME,
                                                                             MST_MasterLocationTable.CODE_FLD, txtMasLoc.Text,
                                                                             htbCriteria, false);
                if (drwResult != null)
                {
                    if (_voMasLoc.MasterLocationID !=
                        int.Parse(drwResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString()))
                    {
                        _voMasLoc.MasterLocationID =
                            int.Parse(drwResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString());
                        ClearForm();
                    }
                    txtMasLoc.Text = drwResult[MST_MasterLocationTable.CODE_FLD].ToString();

                    //reset Modified status
                    txtMasLoc.Modified = false;
                }
                else
                {
                    txtMasLoc.Focus();
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Validate data
        /// </summary>
        /// <returns></returns>
        /// <author>Trada</author>
        /// <date>Tuesday, June 21 2005</date>
        private bool IsValidateData()
        {
            if (_formMode == EnumAction.Add)
            {
                //Check Mandatory
                if (FormControlComponents.CheckMandatory(dtmPostDate))
                {
                    PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                    dtmPostDate.Focus();
                    dtmPostDate.Select();
                    return false;
                }

                //Check date in period
                if (!FormControlComponents.CheckDateInCurrentPeriod(DateTime.Parse(dtmPostDate.Value.ToString())))
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_POSTDATE_PERIOD, MessageBoxIcon.Exclamation);
                    dtmPostDate.Focus();
                    dtmPostDate.Select();
                    return false;
                }
                //check the PostDate smaller than the current date
                if ((DateTime) dtmPostDate.Value > new UtilsBO().GetDBDate())
                {
                    //MessageBox.Show("The Post Date you input is not in the current period");
                    PCSMessageBox.Show(ErrorCode.MESSAGE_INV_TRANSACTION_CANNOT_IN_FUTURE, MessageBoxIcon.Warning);
                    dtmPostDate.Focus();
                    return false;
                }
            }
            if (FormControlComponents.CheckMandatory(cboCCN))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                cboCCN.Focus();
                cboCCN.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtMasLoc))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtMasLoc.Focus();
                txtMasLoc.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtCompletionNo))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtCompletionNo.Focus();
                txtCompletionNo.Select();
                return false;
            }


            if (FormControlComponents.CheckMandatory(txtWO))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtWO.Focus();
                txtWO.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtWOLine))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtWOLine.Focus();
                txtWOLine.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtCompletedQty))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtCompletedQty.Focus();
                txtCompletedQty.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(cboQAStatus))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                cboQAStatus.Focus();
                cboQAStatus.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtPurpose))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtPurpose.Focus();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtLocation))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtLocation.Focus();
                txtLocation.Select();
                return false;
            }

            if (FormControlComponents.CheckMandatory(txtBin))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
                txtBin.Focus();
                return false;
            }

            //If Lot != string.empty then check for Completed Quantity <= LOT Size
            if (txtLot.Text != string.Empty)
            {
                if (Decimal.Parse(txtCompletedQty.Value.ToString()) > _pintLotSize)
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_WOCOMPLETION_COMPQTY_MUST_SMALLER_LOTSIZE,
                                       MessageBoxIcon.Exclamation);
                    txtCompletedQty.Focus();
                    txtCompletedQty.Select();
                    return false;
                }
            }

            //If Serial != string.empty then check for Completed Quantity == 1
            if (txtSerial.Text != string.Empty)
            {
                if (Decimal.Parse(txtCompletedQty.Value.ToString()) != 1)
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_WOCOMPLETION_COMPQTY_MUST_BE_ONE, MessageBoxIcon.Exclamation);
                    txtCompletedQty.Focus();
                    txtCompletedQty.Select();
                    return false;
                }
                //If user inputs Serial then user has to input Lot also.
                if (txtLot.Text.Trim() == string.Empty)
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_WOCOMPLETION_PLS_INPUT_LOT, MessageBoxIcon.Exclamation);
                    txtLot.Focus();
                    txtLot.Select();
                    return false;
                }
            }

            //Display warning message if completed quantity <= 0
            if (Decimal.Parse(txtCompletedQty.Value.ToString()) <= 0)
            {
                PCSMessageBox.Show(ErrorCode.MESSAGE_WOCOMPLETION_COMPQTY_MUST_BE_GREATER_ZERO, MessageBoxIcon.Exclamation);
                txtCompletedQty.Focus();
                txtCompletedQty.Select();
                return false;
            }

            // checking total completion quantity cannot exceed order quantity
            decimal decOrderQuantity = Convert.ToDecimal(txtOrderQuantity.Value);
            decimal decTotalCompletedQuantity = 0;
            decimal decTotalCompleted = 0;
            try
            {
                decTotalCompleted = Convert.ToDecimal(txtTotalCompleted.Value);
            }
            catch
            {
            }
            decTotalCompletedQuantity = decTotalCompleted + Convert.ToDecimal(txtCompletedQty.Value);
            if (_formMode == EnumAction.Edit)
            {
                decTotalCompletedQuantity = decTotalCompletedQuantity - _decOriginCompletedQty;
            }
            if (decOrderQuantity < decTotalCompletedQuantity)
            {
                PCSMessageBox.Show(ErrorCode.MESSAGE_COMPLETION_OVER_ORDER, MessageBoxIcon.Exclamation);
                txtCompletedQty.Focus();
                return false;
            }

            // validate component
            string missingComponentCode;
            btnPrintBOMShortage.Enabled = false;
            if (!_boWoCompletion.IsEnoughComponent(Convert.ToInt32(txtWOLine.Tag), Convert.ToDecimal(txtCompletedQty.Text), out missingComponentCode))
            {
                btnPrintBOMShortage.Enabled = true;
                btnPrintBOMShortage.Focus();
                PCSMessageBox.Show(ErrorCode.MESSAGE_NOT_ENOUGH_QUANTITY_OF_COMPONENT_TO_COMPLETE, MessageBoxIcon.Warning, new[]{missingComponentCode});
                return false;
            }
            return true;
        }

        /// <summary>
        /// txtCompletionNo_Leave
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void txtCompletionNo_Leave(object sender, EventArgs e)
        {
            const string methodName = This + ".txtCompletionNo_Leave()";
            try
            {
                OnLeaveControl(sender, e);
                if (!txtCompletionNo.Modified) return;

                if (txtCompletionNo.Text == string.Empty)
                {
                    ClearForm();
                    if (btnAdd.Enabled)
                    {
                        dtmPostDate.Value = null;
                    }

                    return;
                }
                if (_formMode == EnumAction.Default)
                {
                    var htbCriteria = new Hashtable();
                    DataRowView drwResult = null;
                    //User has enter MasLoc
                    if (txtMasLoc.Text != string.Empty)
                    {
                        htbCriteria.Add(PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD, _voMasLoc.MasterLocationID.ToString());
                    }
                    else //User has not entered MasLoc
                    {
                        PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_MASTERLOCATION, MessageBoxIcon.Error);
                        txtCompletionNo.Text = string.Empty;
                        txtMasLoc.Focus();

                        return;
                    }

                    drwResult = FormControlComponents.OpenSearchForm(VWorkOrderCompletion,
                                                                     PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD,
                                                                     txtCompletionNo.Text.Trim(), htbCriteria, false);
                    if (drwResult != null)
                    {
                        txtCompletionNo.Text = drwResult[PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD].ToString();
                        //Keep valua of WOCompletionID and ProductID
                        lblCompletionNO.Tag = drwResult[PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD];
                        txtCompletionNo.Tag = drwResult[PRO_WorkOrderCompletionTable.PRODUCTID_FLD];
                        FillDataToControlsForView(int.Parse(lblCompletionNO.Tag.ToString()),
                                                  int.Parse(txtCompletionNo.Tag.ToString()));

                        //reset Modified status
                        txtCompletionNo.Modified = false;

                        //Hacked Canhnv
                        _voMasLoc.MasterLocationID =
                            int.Parse(drwResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString());
                        txtWO.Tag = drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD];
                        txtWOLine.Tag = drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD];
                        txtUM.Tag = drwResult[PRO_WorkOrderDetailTable.STOCKUMID_FLD];
                        txtLocation.Tag = drwResult[MST_LocationTable.LOCATIONID_FLD];
                        txtBin.Tag = drwResult[MST_BINTable.BINID_FLD];
                        _pintProductId = (int) drwResult[ITM_ProductTable.PRODUCTID_FLD];
                        //End hacked						
                    }
                    else
                    {
                        txtCompletionNo.Focus();
                    }
                    LockForm();
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// FillDataToControlsForView
        /// </summary>
        /// <param name="pintWOCompletionID"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void FillDataToControlsForView(int pintWOCompletionID, int pintProductID)
        {
            //Load information of item
            var dtbProduct = new DataTable();
            dtbProduct = _boWoCompletion.LoadItemInfo(pintProductID);
            //Load information of WOCompletion
            DataRow drowWOCompletion = _boWoCompletion.LoadWOCompletion(pintWOCompletionID);
            //Bind data to all controls
            dtmPostDate.Value = DateTime.Parse(drowWOCompletion[PRO_WorkOrderCompletionTable.POSTDATE_FLD].ToString());
            if (drowWOCompletion[PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD].ToString() != string.Empty)
            {
                dtmWOCompletionDate.Value =
                    (DateTime) drowWOCompletion[PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD];
            }
            else
                dtmWOCompletionDate.Value = null;
            txtWO.Text = drowWOCompletion[PRO_WorkOrderMasterTable.WORKORDERNO_FLD].ToString();
            txtWO.Tag = drowWOCompletion[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD].ToString();

            txtWOLine.Text = drowWOCompletion[PRO_WorkOrderDetailTable.LINE_FLD].ToString();
            //HACKED: added by Tuan TQ. Get WO Detail ID for printing BOM shortage
            txtWOLine.Tag = drowWOCompletion[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD];
            //End hacked

            txtCompletedQty.Value = drowWOCompletion[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].ToString();
            _decOriginCompletedQty = Convert.ToDecimal(txtCompletedQty.Value);
            // added by dungla 4-July-2008
            txtOrderQuantity.Value = drowWOCompletion[PRO_WorkOrderDetailTable.ORDERQUANTITY_FLD].ToString();
            txtTotalCompleted.Value = _boWoCompletion.GetCompletedQuantity(Convert.ToInt32(txtWO.Tag),
                                                                          Convert.ToInt32(txtWOLine.Tag));
            // end added by dungla 4-July-2008
            try
            {
                txtNGQuantity.Value = drowWOCompletion[PRO_WorkOrderCompletionTable.NGQUANTITY_FLD].ToString();
            }
            catch
            {
            }
            txtLocation.Text = drowWOCompletion[LocationCode].ToString();
            txtBin.Text = drowWOCompletion[BinCode].ToString();
            if (drowWOCompletion[PRO_WorkOrderCompletionTable.LOT_FLD] != null)
            {
                txtLot.Text = drowWOCompletion[PRO_WorkOrderCompletionTable.LOT_FLD].ToString();
                txtSerial.Text = drowWOCompletion[PRO_WorkOrderCompletionTable.SERIAL_FLD].ToString();
            }
            txtUM.Text = dtbProduct.Rows[0][CaptionUm].ToString();
            //Fill data to combo box QAStatus
            int pintQAStatus = 0;
            if (drowWOCompletion[PRO_WorkOrderCompletionTable.QASTATUS_FLD].ToString() != string.Empty)
            {
                pintQAStatus = int.Parse(drowWOCompletion[PRO_WorkOrderCompletionTable.QASTATUS_FLD].ToString());
            }
            else
                pintQAStatus = 0;
            cboQAStatus.SelectedIndex = pintQAStatus;

            txtPartName.Text = dtbProduct.Rows[0][ITM_ProductTable.DESCRIPTION_FLD].ToString();
            txtItem.Text = dtbProduct.Rows[0][ITM_ProductTable.CODE_FLD].ToString();
            txtModel.Text = dtbProduct.Rows[0][ITM_ProductTable.REVISION_FLD].ToString();

            //HACKED: Added by Tuan TQ 09 Dec, 2005. Add properties. 
            txtShift.Text = drowWOCompletion[PRO_ShiftTable.TABLE_NAME + PRO_ShiftTable.SHIFTDESC_FLD].ToString();
            if (drowWOCompletion[PRO_WorkOrderCompletionTable.SHIFTID_FLD].ToString().Trim() != string.Empty)
            {
                txtShift.Tag = drowWOCompletion[PRO_WorkOrderCompletionTable.SHIFTID_FLD];
            }
            else
                txtShift.Tag = 0;

            txtPurpose.Text =
                drowWOCompletion[PRO_IssuePurposeTable.TABLE_NAME + PRO_IssuePurposeTable.DESCRIPTION_FLD].ToString();
            txtPurpose.Tag = drowWOCompletion[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD];

            txtRemark.Text = drowWOCompletion[PRO_WorkOrderCompletionTable.REMARK_FLD].ToString();
            //End hacked
        }

        /// <summary>
        /// OnEnterControl
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void OnEnterControl(object sender, EventArgs e)
        {
            const string methodName = This + ".OnEnterControl()";
            try
            {
                FormControlComponents.OnEnterControl(sender, e);
            }
            catch (PCSException ex)
            {
                throw new PCSException(ex.mCode, methodName, ex);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// OnLeaveControl
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void OnLeaveControl(object sender, EventArgs e)
        {
            const string methodName = This + ".OnEnterControl()";
            try
            {
                FormControlComponents.OnLeaveControl(sender, e);
            }
            catch (PCSException ex)
            {
                throw new PCSException(ex.mCode, methodName, ex);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// txtMasLoc_KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void txtMasLoc_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtMasLoc_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4 && btnSearchMasLoc.Enabled)
                {
                    btnSearchMasLoc_Click(sender, e);
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// txtCompletionNo_KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void txtCompletionNo_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtCompletionNo_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4 && btnSearchCompletionNo.Enabled)
                {
                    btnSearchCompletionNo_Click(sender, e);
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// txtWO_KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void txtWO_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtWO_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4 && btnSearchWO.Enabled)
                {
                    btnSearchWO_Click(sender, e);
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// txtWOLine_KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void txtWOLine_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtWOLine_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4 && btnSearchWOLine.Enabled)
                {
                    btnSearchWOLine_Click(sender, e);
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// txtLocation_KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, June 22 2005</date>
        private void txtLocation_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtLocation_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4 && btnSearchLocation.Enabled)
                {
                    SelectLocation(true);
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// txtBin_KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Tuan TQ</author>
        /// <date>03 Apr 2006</date>
        private void txtBin_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtBin_KeyDown()";

            try
            {
                if ((e.KeyCode == Keys.F4) && (btnSearchBin.Enabled))
                {
                    SelectBin(true);
                }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <date>03 Apr 2006</date>
        private void txtBin_Validating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".txtBin_Validating()";

            try
            {
                //exit if not in add action or empty
                if (!btnSave.Enabled) return;

                if (txtBin.Text.Trim().Length == 0)
                {
                    txtBin.Tag = null;
                    return;
                }
                else if (!txtBin.Modified)
                {
                    return;
                }

                e.Cancel = !SelectBin(false);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Exclamation);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Exclamation);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtLocation_Validating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".txtLocation_Validating()";

            try
            {
                //exit if not in add action or empty
                if (!btnSave.Enabled) return;

                if (txtLocation.Text.Trim().Length == 0)
                {
                    txtLocation.Tag = null;

                    txtBin.Text = string.Empty;
                    txtBin.Tag = null;
                    return;
                }
                else if (!txtLocation.Modified)
                {
                    return;
                }

                e.Cancel = !SelectLocation(false);
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtWO_Validating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".txtWO_Validating()";
            try
            {
                if (!txtWO.Modified) return;

                if (txtWO.Text == string.Empty)
                {
                    ClearFormWhenChangeWOLine();
                    dtmWOCompletionDate.Value = null;
                    txtWOLine.Text = string.Empty;
                    return;
                }

                DataRowView drwResult = null;
                var htbCriteria = new Hashtable();
                if (txtMasLoc.Text != string.Empty)
                {
                    htbCriteria.Add(PRO_WorkOrderMasterTable.MASTERLOCATIONID_FLD, _voMasLoc.MasterLocationID.ToString());
                }
                else //User has not entered MasLoc
                {
                    e.Cancel = true;
                    return;
                }

                htbCriteria.Add(PRO_WorkOrderDetailTable.STATUS_FLD, (int) WOLineStatus.Released);
                if (txtFGoodsCode.Text.Trim() == string.Empty)
                {
                    drwResult = FormControlComponents.OpenSearchForm(VWorelease,
                                                                     PRO_WorkOrderMasterTable.WORKORDERNO_FLD,
                                                                     txtWO.Text.Trim(), htbCriteria, false);
                }
                else
                {
                    drwResult = FormControlComponents.OpenSearchForm(VWoreleasefgoodscode,
                                                                     PRO_WorkOrderMasterTable.WORKORDERNO_FLD,
                                                                     txtWO.Text.Trim(), htbCriteria, false);
                }
                if (drwResult != null)
                {
                    if (!drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD].Equals(txtWO.Tag))
                    {
                        txtWO.Tag = drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD];
                        ClearFormWhenChangeWOLine();
                        dtmWOCompletionDate.Value = null;
                        txtWOLine.Text = string.Empty;
                    }
                    txtWO.Text = drwResult[PRO_WorkOrderMasterTable.WORKORDERNO_FLD].ToString();
                    lblWO.Tag = drwResult[PRO_WorkOrderMasterTable.PRODUCTIONLINEID_FLD];
                    //reset Modified status
                    txtWO.Modified = false;
                }
                else
                    e.Cancel = true;
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtWOLine_Validating(object sender, CancelEventArgs e)
        {
            if (lblWO.Tag == null)
            {
                MessageBox.Show("Hãy nhập lệnh sản xuất cho XN");
                txtWO.Focus();
                return;
            }
            const string methodName = This + ".txtWOLine_Validating()";
            try
            {
                var htbCriteria = new Hashtable();
                htbCriteria.Add(PRO_WorkOrderDetailTable.PRODUCTIONLINEID_FLD, lblWO.Tag.ToString());
                DataRowView drwResult = null;

                if (!txtWOLine.Modified) return;
                if (txtWOLine.Text == string.Empty)
                {
                    ClearFormWhenChangeWOLine();
                    txtWOLine.Text = string.Empty;

                    //HACKED added by Tuan TQ. Enable/Disable print BOM shortage
                    btnPrintBOMShortage.Enabled = false;
                    //End hacked
                    return;
                }

                //User has entered Work Order Master
                if (txtWO.Text != string.Empty)
                {
                    htbCriteria.Add(PRO_WorkOrderDetailTable.WORKORDERMASTERID_FLD, txtWO.Tag);
                    htbCriteria.Add(PRO_WorkOrderDetailTable.STATUS_FLD, (int) WOLineStatus.Released);
                }
                else //User has not entered Work Order Master
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_WOROUTING_INPUT_WORKORDER_FIRST, MessageBoxIcon.Error);
                    txtWOLine.Text = string.Empty;
                    txtWO.Focus();

                    //HACKED added by Tuan TQ. Enable/Disable print BOM shortage
                    btnPrintBOMShortage.Enabled = false;
                    //End hacked

                    return;
                }

                drwResult = FormControlComponents.OpenSearchForm(VWocompletion, PRO_WorkOrderDetailTable.LINE_FLD,
                                                                 txtWOLine.Text.Trim(), htbCriteria, false);
                if (drwResult != null)
                {
                    if (!drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD].Equals(txtWOLine.Tag))
                    {
                        txtWOLine.Tag = drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD];
                        ClearFormWhenChangeWOLine();
                    }

                    _intProductionLineId = (int) drwResult[PRO_ProductionLineTable.PRODUCTIONLINEID_FLD];
                    if (dtmPostDate.Value != DBNull.Value && dtmPostDate.Value != null)
                        FillWOCompletionDate((DateTime) dtmPostDate.Value, _intProductionLineId);

                    txtWOLine.Text = drwResult[PRO_WorkOrderDetailTable.LINE_FLD].ToString();

                    //reset Modified status
                    txtWOLine.Modified = false;

                    new WorkOrderCompletionBO().ListLocationIssueAndOH(
                        int.Parse(drwResult[PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD].ToString()), 1000);
                    _pintProductId = int.Parse(drwResult[PRO_WorkOrderDetailTable.PRODUCTID_FLD].ToString());

                    //FillDataToControls
                    txtItem.Text = drwResult[PARTNUMBER].ToString();
                    txtPartName.Text = drwResult[Partname].ToString();
                    txtModel.Text = drwResult[Model].ToString();

                    //Fill data to OpenQuantity
                    decimal pdecComplettedQuantity, pdecScrapQuantity;
                    if (drwResult[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].ToString() != string.Empty)
                        pdecComplettedQuantity =
                            decimal.Parse(drwResult[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].ToString());
                    else
                        pdecComplettedQuantity = 0;
                    if (drwResult[PRO_AOScrapDetailTable.SCRAPQUANTITY_FLD].ToString() != string.Empty)
                        pdecScrapQuantity = decimal.Parse(drwResult[PRO_AOScrapDetailTable.SCRAPQUANTITY_FLD].ToString());
                    else
                        pdecScrapQuantity = 0;
                    decimal decOrderQuantity =
                        decimal.Parse(drwResult[PRO_WorkOrderDetailTable.ORDERQUANTITY_FLD].ToString()) -
                        pdecComplettedQuantity - pdecScrapQuantity;
                    _pdecQuantity = decOrderQuantity - pdecComplettedQuantity - pdecScrapQuantity;
                    txtCompletedQty.Value = _pdecQuantity;
                    // store the order quantity in order to check total completed quantity
                    txtOrderQuantity.Value = decOrderQuantity;
                    txtTotalCompleted.Value = pdecComplettedQuantity;
                    //Fill data to UM label
                    txtUM.Text = drwResult[CaptionUm].ToString();
                    //Keep value of StockUMID
                    txtUM.Tag = drwResult[PRO_WorkOrderDetailTable.STOCKUMID_FLD];
                    //Set value for pintLotSize
                    if (drwResult[ITM_ProductTable.LOTSIZE_FLD].ToString() == string.Empty)
                        _pintLotSize = 0;
                    else
                        _pintLotSize = int.Parse(drwResult[ITM_ProductTable.LOTSIZE_FLD].ToString());
                    //Save MasterLocationID default
                    if (drwResult[ITM_ProductTable.MASTERLOCATIONID_FLD].ToString() != string.Empty)
                        ;
                    else
                        ;

                    //Fill data to combo box QAStatus
                    int pintQAStatus = 0;
                    if (drwResult[ITM_ProductTable.QASTATUS_FLD].ToString().Trim() != string.Empty ||
                        drwResult[ITM_ProductTable.QASTATUS_FLD] != DBNull.Value)
                        pintQAStatus = int.Parse(drwResult[ITM_ProductTable.QASTATUS_FLD].ToString());
                    switch (pintQAStatus)
                    {
                        case (int) EnumQA.NOT_REQUIRE_INSPECTION:
                            cboQAStatus.SelectedIndex = (int) QAStatusEnum.Passed;
                            break;
                        default:
                            cboQAStatus.SelectedIndex = (int) QAStatusEnum.Unknow;
                            break;
                    }
                    cboQAStatus.Enabled = false;
                }
                else
                {
                    txtWOLine.Focus();

                    //HACK: added by Tuan TQ. Enable/Disable print BOM shortage
                    btnPrintBOMShortage.Enabled = false;
                    //End hack
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// dtmPostDate_Validating
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Wednesday, July 19 2006</date>
        private void dtmPostDate_Validating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".dtmPostDate_Validating()";
            try
            {
                if (txtWO.Text.Trim() != string.Empty && dtmPostDate.Value != DBNull.Value)
                {
                    //Fill WOCompletionDate
                    FillWOCompletionDate((DateTime) dtmPostDate.Value, _intProductionLineId);
                }
                else
                {
                    dtmWOCompletionDate.Value = null;
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnEdit_Click()";
            try
            {
                if (txtCompletionNo.Text.Trim() != string.Empty)
                {
                    _formMode = EnumAction.Edit;
                    LockForm();
                }
                else
                {
                    return;
                }
            }
            catch
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ErrorCode.MSG_LABORTIME_SELECTWOMASTER, MessageBoxIcon.Information);
                return;
            }
        }

        private void LockForm()
        {
            switch (_formMode)
            {
                case EnumAction.Add:
                    txtWO.Enabled = true;
                    txtWOLine.Enabled = true;
                    txtCompletedQty.Enabled = true;
                    txtLocation.Enabled = true;
                    cboQAStatus.Enabled = false;
                    txtShift.Enabled = true;
                    txtPurpose.Enabled = true;
                    txtRemark.Enabled = true;
                    txtBin.Enabled = true;
                    txtCompletionNo.Enabled = false;
                    txtMasLoc.Enabled = true;
                    txtFGoodsCode.Enabled = true;

                    dtmPostDate.Enabled = true;

                    btnPurpose.Enabled = true;
                    btnSearchLocation.Enabled = true;
                    btnSearchWO.Enabled = true;
                    btnSearchWOLine.Enabled = true;
                    btnSearchCompletionNo.Enabled = false;
                    btnShift.Enabled = true;
                    btnSearchBin.Enabled = true;
                    btnSearchWO.Enabled = true;
                    btnFGoodsCode.Enabled = true;

                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnPrint.Enabled = false;
                    btnPrintBOMShortage.Enabled = false;
                    btnSave.Enabled = true;
                    btnDelete.Enabled = false;


                    break;
                case EnumAction.Edit:
                    txtCompletedQty.Enabled = true;
                    txtLocation.Enabled = true;
                    txtBin.Enabled = true;
                    txtCompletionNo.Enabled = false;
                    txtWO.Enabled = false;
                    txtWOLine.Enabled = false;
                    cboQAStatus.Enabled = false;
                    txtShift.Enabled = false;
                    txtPurpose.Enabled = false;
                    txtRemark.Enabled = true;
                    txtMasLoc.Enabled = false;
                    txtFGoodsCode.Enabled = false;

                    dtmPostDate.Enabled = false;

                    btnPurpose.Enabled = false;
                    btnShift.Enabled = false;
                    btnSearchLocation.Enabled = true;
                    btnSearchWO.Enabled = false;
                    btnSearchWOLine.Enabled = false;
                    btnSearchCompletionNo.Enabled = false;
                    btnSearchBin.Enabled = true;
                    btnSearchWO.Enabled = false;
                    btnFGoodsCode.Enabled = false;

                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnPrint.Enabled = false;
                    btnPrintBOMShortage.Enabled = false;
                    btnSave.Enabled = true;
                    btnDelete.Enabled = false;

                    break;
                case EnumAction.Default:
                    txtWO.Enabled = false;
                    txtWOLine.Enabled = false;
                    txtCompletedQty.Enabled = false;
                    txtLocation.Enabled = false;
                    cboQAStatus.Enabled = false;
                    txtCompletionNo.Enabled = true;
                    txtShift.Enabled = false;
                    txtPurpose.Enabled = false;
                    txtRemark.Enabled = false;
                    txtBin.Enabled = false;
                    txtFGoodsCode.Enabled = false;

                    dtmPostDate.Enabled = false;

                    btnPurpose.Enabled = false;
                    btnShift.Enabled = false;
                    btnSearchLocation.Enabled = false;
                    btnSearchWO.Enabled = true;
                    btnSearchWOLine.Enabled = false;
                    btnSearchCompletionNo.Enabled = true;
                    btnSearchBin.Enabled = false;
                    btnSearchWO.Enabled = false;
                    btnFGoodsCode.Enabled = false;

                    btnAdd.Enabled = true;
                    btnSave.Enabled = false;
                    if (lblCompletionNO.Tag != null || txtCompletionNo.Text.Trim() != string.Empty)
                    {
                        btnEdit.Enabled = true;
                        btnPrint.Enabled = true;
                        btnPrintBOMShortage.Enabled = true;
                        btnDelete.Enabled = true;
                    }
                    else
                    {
                        btnEdit.Enabled = false;
                        btnPrint.Enabled = false;
                        btnPrintBOMShortage.Enabled = false;
                        btnDelete.Enabled = false;
                    }
                    break;
            }
            //End hacked			
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnDelete_Click()";
            if (txtCompletionNo.Text.Trim() == string.Empty)
            {
                return;
            }
            if (PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                DialogResult.Yes)
            {
                try
                {
                    //call the BO class to delete
                    var objWOCompletionBO = new WorkOrderCompletionBO();
                    objWOCompletionBO.DeleteWOCompletion((int) lblCompletionNO.Tag);


                    //After deleting, clean environment
                    lblCompletionNO.Tag = null; //No product after deleting

                    //Turn to default action
                    _formMode = EnumAction.Default;

                    //clear controls
                    ClearForm();

                    //lock form
                    LockForm();

                    //focus
                    txtCompletionNo.Focus();
                }
                catch (PCSException ex)
                {
                    // displays the error message.
                    PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                    // log message.
                    try
                    {
                        Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                    }
                    catch
                    {
                        PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    // displays the error message.
                    PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                    // log message.
                    try
                    {
                        Logger.LogMessage(ex, methodName, Level.ERROR);
                    }
                    catch
                    {
                        PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                    }
                }
            }
        }


        private void btnFGoodsCode_Click(object sender, EventArgs e)
        {
            const string methodName = This + ".btnFGoodsCode_Click()";
            try
            {
                DataRowView drwResult = null;
                var strWhere = SO_SaleOrderDetailTable.TABLE_NAME + "." + SO_SaleOrderDetailTable.SHIPCOMPLETED_FLD +
                           "= 0 OR "
                           + SO_SaleOrderDetailTable.TABLE_NAME + "." + SO_SaleOrderDetailTable.SHIPCOMPLETED_FLD +
                           " is null ";

                drwResult = FormControlComponents.OpenSearchFormWithWhere(SO_SaleOrderDetailTable.TABLE_NAME,
                                                                          SO_SaleOrderDetailTable.FGOODSCODE_FLD,
                                                                          txtFGoodsCode.Text.Trim(), strWhere, true);
                if (drwResult != null)
                {
                    lblFGoodsCode.Tag = int.Parse(drwResult[SO_SaleOrderDetailTable.SALEORDERDETAILID_FLD].ToString());
                    txtFGoodsCode.Text = drwResult[SO_SaleOrderDetailTable.FGOODSCODE_FLD].ToString();
                }
            }
            catch (PCSException ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtFGoodsCode_TextChanged(object sender, EventArgs e)
        {
        }

        private void txtFGoodsCode_Validating(object sender, CancelEventArgs e)
        {
            const string methodName = This + ".txtFGoodsCode_Validating()";
            try
            {
                DataRowView drwResult = null;
                String strWhere = String.Empty;
                strWhere = SO_SaleOrderDetailTable.TABLE_NAME + "." + SO_SaleOrderDetailTable.SHIPCOMPLETED_FLD +
                           "= 0 OR "
                           + SO_SaleOrderDetailTable.TABLE_NAME + "." + SO_SaleOrderDetailTable.SHIPCOMPLETED_FLD +
                           " is null ";

                drwResult = FormControlComponents.OpenSearchFormWithWhere(SO_SaleOrderDetailTable.TABLE_NAME,
                                                                          SO_SaleOrderDetailTable.FGOODSCODE_FLD,
                                                                          txtFGoodsCode.Text.Trim(), strWhere, false);
                if (drwResult != null)
                {
                    lblFGoodsCode.Tag = int.Parse(drwResult[SO_SaleOrderDetailTable.SALEORDERDETAILID_FLD].ToString());
                    txtFGoodsCode.Text = drwResult[SO_SaleOrderDetailTable.FGOODSCODE_FLD].ToString();
                }
            }
            catch (PCSException ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtFGoodsCode_KeyDown(object sender, KeyEventArgs e)
        {
            const string methodName = This + ".txtFGoodsCode_KeyDown()";
            try
            {
                if (e.KeyCode == Keys.F4 && btnFGoodsCode.Enabled)
                {
                    btnFGoodsCode_Click(sender, e);
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, methodName, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, methodName, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }
    }
}